<template>
  <div class="ticket-management-container">
    <el-card class="ticket-management-card">
      <template #header>
        <div class="card-header">
          <span>票务管理系统</span>
          <el-button type="primary" @click="handleAddTicket">
            <el-icon><Plus /></el-icon>
            添加票务
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入票务名称或编号进行搜索"
          prefix-icon="Search"
          class="search-input"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      
      <!-- 票务列表 -->
      <el-table
        v-loading="loading"
        :data="filteredTickets"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="票务ID" width="80" />
        <el-table-column label="海报" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.poster"
              :src="scope.row.poster"
              :preview-src-list="[scope.row.poster]"
              style="width: 80px; height: 80px; object-fit: cover;"
              fit="cover"
            />
            <span v-else class="no-poster">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="票务名称" width="160" />
        <el-table-column prop="category.name" label="类别" width="100" />
        <el-table-column prop="startTime" label="开始时间" width="160" />        
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'available' ? 'success' : 'danger'"
            >
              {{ scope.row.status === 'available' ? '可用' : '已售罄' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="艺人" width="250">
          <template #default="scope">
            <div v-if="scope.row.artists && scope.row.artists.length > 0">
              <el-tag v-for="(artist, index) in scope.row.artists" :key="index" type="info" style="margin: 2px;">{{ artist }}</el-tag>
            </div>
            <span v-else class="no-artists">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>          
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditTicket(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteTicket(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTickets.length"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑票务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="ticketFormRef"
        :model="ticketForm"
        :rules="ticketRules"
        label-width="100px"
      >
        <el-form-item label="票务名称" prop="name">
          <el-input v-model="ticketForm.name" placeholder="请输入票务名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input
            v-model="ticketForm.price"
            type="number"
            placeholder="请输入价格"
            min="0"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input
            v-model="ticketForm.stock"
            type="number"
            placeholder="请输入库存"
            min="0"
            step="1"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="ticketForm.status" placeholder="请选择状态">
            <el-option label="可用" value="available" />
            <el-option label="已售罄" value="soldOut" />
          </el-select>
        </el-form-item>
        <el-form-item label="海报">
          <el-upload
            v-model:file-list="fileList"
            :auto-upload="false"
            :on-change="handleFileChange"
            list-type="picture-card"
            accept="image/*"
          >
            <template #default>
              <el-icon><Plus /></el-icon>
            </template>
            <template #file="{ file }">
              <img :src="file.url" alt="海报" class="upload-image" />
              <div class="el-upload__actions">
                <el-icon class="el-upload__action" @click.stop="handleRemovePoster"><Delete /></el-icon>
              </div>
            </template>
          </el-upload>
          <div class="upload-tip">支持 JPG、PNG 格式，建议尺寸 300x400px</div>
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="ticketForm.category" placeholder="请选择类别">
            <el-option
              v-for="category in ticketCategories"
              :key="category.id"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="ticketForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="ticketForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="演出艺人">
          <el-input
            v-model="artistsInput"
            placeholder="输入艺人名称，按回车添加"
            @keyup.enter="addArtist"
            style="margin-bottom: 10px;"
          />
          <div v-if="ticketForm.artists.length > 0" class="artists-list">
            <el-tag
              v-for="(artist, index) in ticketForm.artists"
              :key="index"
              type="info"
              closable
              @close="removeArtist(index)"
            >
              {{ artist }}
            </el-tag>
          </div>
          <div v-else class="no-artists-tip">暂无艺人信息，输入艺人名称后按回车添加</div>
        </el-form-item>
        <el-form-item label="详细描述">
          <el-input
            v-model="ticketForm.description"
            type="textarea"
            placeholder="请输入票务详细描述、演出内容、注意事项等信息"
            rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除该票务吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Search, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getAllTicketCategories } from '../api/category.js'
import { getAllTickets, addTicket, updateTicket, deleteTicket } from '../api/ticket.js'

export default {
  name: 'TicketManagement',
  components: {
    Plus,
    Search,
    Delete
  },
  setup() {
    // 状态管理
    const loading = ref(false)
    const tickets = ref([])
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const dialogVisible = ref(false)
    const deleteDialogVisible = ref(false)
    const dialogTitle = ref('')
    const editingTicketId = ref(null)
    const ticketFormRef = ref(null)
    const ticketCategories = ref([])
    
    // 表单数据
    const ticketForm = reactive({
      name: '',
      price: 0,
      stock: 0,
      status: 'available',
      description: '',
      poster: '',
      category: '',
      startTime: '',
      endTime: '',
      artists: []
    })
    
    // 上传文件列表
    const fileList = ref([])
    
    // 表单验证规则
    const ticketRules = {
      name: [
        { required: true, message: '请输入票务名称', trigger: 'blur' },
        { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            const numValue = parseFloat(value);
            if (isNaN(numValue) || numValue < 0) {
              callback(new Error('价格不能小于0'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
      stock: [
        { required: true, message: '请输入库存', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            const numValue = parseInt(value);
            if (isNaN(numValue) || numValue < 0) {
              callback(new Error('库存不能小于0'));
            } else if (!Number.isInteger(numValue)) {
              callback(new Error('库存必须为整数'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ],
      category: [
        { required: true, message: '请选择类别', trigger: 'change' }
      ],
      startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' }
      ]
    }
    
    // 艺人输入框
    const artistsInput = ref('')
    
    // 添加艺人
    const addArtist = () => {
      const artist = artistsInput.value.trim()
      if (artist && !ticketForm.artists.includes(artist)) {
        ticketForm.artists.push(artist)
        artistsInput.value = ''
      }
    }
    
    // 移除艺人
    const removeArtist = (index) => {
      ticketForm.artists.splice(index, 1)
    }
    
    // 过滤后的票务列表
    const filteredTickets = computed(() => {
      if (!searchKeyword.value) {
        return tickets.value
      }
      const keyword = searchKeyword.value.toLowerCase()
      return tickets.value.filter(ticket => 
        ticket.name.toLowerCase().includes(keyword) || 
        ticket.id.toString().includes(keyword) ||
        (ticket.category && ticket.category.toLowerCase().includes(keyword)) ||
        (ticket.artists && ticket.artists.some(artist => artist.toLowerCase().includes(keyword)))
      )
    })
    
    // 分页后的票务列表
    const paginatedTickets = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredTickets.value.slice(start, end)
    })
    
    // 初始化数据
    const initData = async () => {
      try {
        loading.value = true
        const ticketList = await getAllTickets()
        console.log('获取票务列表成功:', ticketList)
        tickets.value = ticketList
      } catch (error) {
        console.error('初始化票务数据失败:', error)
        ElMessage.error('初始化票务数据失败')
        // 加载失败时使用模拟数据
        tickets.value = [
          {
            id: 1,
            name: '周杰伦演唱会',
            price: 380.00,
            stock: 100,
            status: 'available',
            description: '2024周杰伦嘉年华世界巡回演唱会门票，包含经典曲目演唱，豪华舞台效果，互动环节等精彩内容。演出时长约150分钟，提前1小时入场。',
            createdAt: '2024-01-15 10:30:00',
            poster: 'https://picsum.photos/seed/concert1/300/400',
            category: 'concert',
            startTime: '2024-03-15 19:30',
            endTime: '2024-03-15 22:00',
            artists: ['周杰伦']
          },
          {
            id: 2,
            name: 'NBA季后赛门票',
            price: 880.00,
            stock: 50,
            status: 'available',
            description: '2024 NBA季后赛门票，湖人VS勇士巅峰对决，感受顶级篮球赛事的魅力。场馆提供餐饮服务，禁止携带专业相机入场。',
            createdAt: '2024-01-16 14:20:00',
            poster: 'https://picsum.photos/seed/basketball1/300/400',
            category: 'sports',
            startTime: '2024-04-10 10:00',
            endTime: '2024-04-10 12:30',
            artists: ['勒布朗·詹姆斯', '库里']
          },
          {
            id: 3,
            name: '复仇者联盟5首映',
            price: 120.00,
            stock: 0,
            status: 'soldOut',
            description: '复仇者联盟5：终局之战首映IMAX电影票，漫威宇宙最新力作，震撼视觉效果。IMAX厅提供最佳观影体验，提前30分钟入场。',
            createdAt: '2024-01-17 09:15:00',
            poster: 'https://picsum.photos/seed/movie1/300/400',
            category: 'movie',
            startTime: '2024-05-01 00:00',
            endTime: '2024-05-01 02:30',
            artists: ['小罗伯特·唐尼', '克里斯·埃文斯']
          },
          {
            id: 4,
            name: '上海迪士尼一日票',
            price: 599.00,
            stock: 200,
            status: 'available',
            description: '上海迪士尼乐园一日门票，含所有游乐设施，七大主题园区任您探索。推荐提前规划行程，热门项目可能需要排队，夏季注意防晒。',
            createdAt: '2024-01-18 11:30:00',
            poster: 'https://picsum.photos/seed/disney1/300/400',
            category: 'amusement',
            startTime: '2024-06-15 08:00',
            endTime: '2024-06-15 22:00',
            artists: ['米老鼠', '唐老鸭']
          },
          {
            id: 5,
            name: '国家大剧院音乐会',
            price: 480.00,
            stock: 80,
            status: 'available',
            description: '贝多芬第九交响曲音乐会门票，由著名指挥家带领国家交响乐团现场演奏，感受古典音乐的魅力。场馆内禁止携带饮料和食物。',
            createdAt: '2024-01-19 16:45:00',
            poster: 'https://picsum.photos/seed/music1/300/400',
            category: 'music',
            startTime: '2024-07-20 19:00',
            endTime: '2024-07-20 21:30',
            artists: ['贝多芬', '国家交响乐团']
          }
        ]
      } finally {
        loading.value = false
      }
    }
    
    // 添加票务
    const handleAddTicket = () => {
      dialogTitle.value = '添加票务'
      editingTicketId.value = null
      // 重置表单
      Object.assign(ticketForm, {
        name: '',
        price: 0,
        stock: 0,
        status: 'available',
        description: '',
        poster: '',
        category: '',
        startTime: '',
        endTime: '',
        artists: []
      })
      // 清空文件列表和艺人输入
      fileList.value = []
      artistsInput.value = ''
      // 重置表单验证
      if (ticketFormRef.value) {
        ticketFormRef.value.resetFields()
      }
      dialogVisible.value = true
    }
    
    // 编辑票务
    const handleEditTicket = (ticket) => {
      dialogTitle.value = '编辑票务'
      editingTicketId.value = ticket.id
      // 填充表单数据
      Object.assign(ticketForm, {
        name: ticket.name,
        price: ticket.price,
        stock: ticket.stock,
        status: ticket.status,
        description: ticket.description,
        poster: ticket.poster || '',
        category: ticket.category || '',
        startTime: ticket.startTime || '',
          endTime: ticket.endTime || '',
        artists: ticket.artists ? [...ticket.artists] : []
      })
      // 初始化文件列表和清空艺人输入
      fileList.value = ticket.poster ? [{ url: ticket.poster }] : []
      artistsInput.value = ''
      dialogVisible.value = true
    }
    
    // 删除票务
    const handleDeleteTicket = (id) => {
      editingTicketId.value = id
      deleteDialogVisible.value = true
    }
    
    // 确认删除
    const handleConfirmDelete = async () => {
      try {
        loading.value = true
        await deleteTicket(editingTicketId.value)
        await initData() // 重新加载数据
        deleteDialogVisible.value = false
        ElMessage.success('票务删除成功')
      } catch (error) {
        console.error('删除票务失败:', error)
        ElMessage.error('票务删除失败')
      } finally {
        loading.value = false
      }
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!ticketFormRef.value) return
      
      // 先尝试转换价格和库存为正确的数字类型
      // 价格转换为浮点数，库存转换为整数
      const parsedPrice = parseFloat(ticketForm.price)
      const parsedStock = parseInt(ticketForm.stock)
      
      // 基本验证
      if (isNaN(parsedPrice) || parsedPrice < 0) {
        ElMessage.error('请输入有效的价格')
        return
      }
      
      if (isNaN(parsedStock) || parsedStock < 0 || !Number.isInteger(parsedStock)) {
        ElMessage.error('请输入有效的整数库存')
        return
      }
      
      // 更新表单中的值为正确的数字类型
      ticketForm.price = parsedPrice
      ticketForm.stock = parsedStock
      
      ticketFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            const ticketData = {
              ...ticketForm,
              status: ticketForm.stock > 0 ? 'available' : 'soldOut'
            }
            
            if (editingTicketId.value) {
              // 编辑操作
              await updateTicket(editingTicketId.value, ticketData)
              ElMessage.success('票务更新成功')
            } else {
              // 添加操作
              await addTicket(ticketData)
              ElMessage.success('票务添加成功')
            }
            
            await initData() // 重新加载数据
            dialogVisible.value = false
          } catch (error) {
            console.error('提交票务失败:', error)
            ElMessage.error(editingTicketId.value ? '票务更新失败' : '票务添加失败')
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1 // 重置到第一页
    }
    
    // 重置搜索
    const handleReset = () => {
      searchKeyword.value = ''
      currentPage.value = 1
    }
    

    
    // 获取票务类别
    const fetchTicketCategories = async () => {
      const result = await getAllTicketCategories()
      if (result.success) {
        console.log('获取票务类别成功:', result.data)
        ticketCategories.value = result.data
      }
    }
    
    // 组件挂载时初始化数据
    onMounted(async () => {
      await fetchTicketCategories()
      initData()
    })
    
    // 处理文件变化
    const handleFileChange = (file) => {
      // 使用 FileReader 读取文件内容
      const reader = new FileReader()
      reader.onload = (e) => {
        ticketForm.poster = e.target.result
      }
      reader.readAsDataURL(file.raw)
    }
    
    // 移除海报
    const handleRemovePoster = () => {
      ticketForm.poster = ''
      fileList.value = []
    }
    
    return {
      loading,
      tickets,
      searchKeyword,
      currentPage,
      pageSize,
      dialogVisible,
      deleteDialogVisible,
      dialogTitle,
      editingTicketId,
      ticketFormRef,
      ticketForm,
      ticketRules,
      ticketCategories,
      filteredTickets,
      paginatedTickets,
      fileList,
      artistsInput,
      addArtist,
      removeArtist,
      handleAddTicket,
      handleEditTicket,
      handleDeleteTicket,
      handleConfirmDelete,
      handleSubmit,
      handleSearch,
      handleReset,
      handleFileChange,
      handleRemovePoster,
      fetchTicketCategories
    }
  }
}
</script>

<style scoped>
.ticket-management-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.ticket-management-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.no-poster {
  display: inline-block;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  background-color: #f5f5f5;
  color: #999;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.no-artists {
  color: #999;
}

.artists-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.no-artists-tip {
  font-size: 12px;
  color: #999;
  padding: 5px 0;
}
</style>